package com.tvshows.front.listener.command;

import org.apache.log4j.Logger;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.swt.widgets.Display;

import com.tvshows.interactions.ObserverBdd;
import com.tvshows.structure.bdd.BddQueries;
import com.tvshows.structure.beans.Favorite;

/**
 * @author tMidy
 * <p>
 * Job Thats Interacts with the {@link ObserverBdd} to refresh the UI
 * </p>
 */
public class RefreshJob
    extends Job
{

    /**
     * The Logger
     */
    private static final Logger LOGGER = Logger.getLogger( RefreshJob.class );

    /**
     * Default constructor
     * 
     * @param name name of the job
     */
    public RefreshJob( String name )
    {
        super( name );
    }

    /**
     * Used constructor
     */
    public RefreshJob()
    {
        this( "RefreshJob" );
    }

    /**
     * @see org.eclipse.core.runtime.jobs.Job#run(org.eclipse.core.runtime.IProgressMonitor)
     */
    @Override
    protected IStatus run( IProgressMonitor arg0 )
    {
        BddQueries.getBddQueries().setJobRunning( true );
        try
        {
            ObserverBdd.getObserverBdd().loadFavoriteDownload( this );
        }
        catch ( Exception e )
        {
            LOGGER.error( e );
        }
        deactivateProgress();
        BddQueries.getBddQueries().setJobRunning( false );
        return Status.OK_STATUS;

    }

    /**
     * Deactivates the progress refresh
     */
    private void deactivateProgress()
    {
        Display.getDefault().asyncExec( new Runnable()
        {
            @Override
            public void run()
            {
                try
                {
                    ObserverBdd.getObserverBdd().activate( false );
                }
                catch ( Exception e )
                {
                    LOGGER.error( e );
                }
            }
        } );
    }

    /**
     * Calls the command to add a favorite to the recap table
     * 
     * @param favorite the favorite to add
     */
    public void addToTable( final Favorite favorite )
    {
        Display.getDefault().asyncExec( new Runnable()
        {
            @Override
            public void run()
            {
                try
                {
                    ObserverBdd.getObserverBdd().addToTable( favorite );
                }
                catch ( Exception e )
                {
                    LOGGER.error( e );
                }
            }
        } );
    }

}
